package com.jiguang.shangcheng.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter("/shang/*")
public class Login implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest reqq = (HttpServletRequest)req;
        HttpServletResponse respp = (HttpServletResponse) resp;
        //设置字符集
        reqq.setCharacterEncoding("UTF-8");
        respp.setContentType("text/html;charset=utf-8");
        HttpSession session = reqq.getSession();
        String flag = (String) session.getAttribute("isLogin");
        //排除不需要过滤的文件例如login.jsp;
        String request_url = reqq.getRequestURI();
        String ctxPath = reqq.getContextPath();
        String url = request_url.substring(ctxPath.length());
        if (url.contains("shang_")){
            if (flag != null && (flag.equals("1") || flag.equals("2"))){
                chain.doFilter(reqq, respp);
            }else{
                PrintWriter out = respp.getWriter();
                out.println("<script>alert('请先进行登录');location.href='/shang/login.jsp';</script>");
            }
        }else{
            chain.doFilter(reqq, respp);
        }
        return;
        //不通过则直接写一个return;
        //chain.doFilter(reqq, respp);//通过则使用这条数据。
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
